package com.hshit.downloader.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.graphics.PorterDuff.Mode;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hshit.downloader.R;
import com.hshit.downloader.adapter.DownLoadAdapter;
import com.hshit.downloader.adapter.DownLoadAdapter.CallBackPressDownload;
import com.hshit.downloader.custom.LoadMoreListView;
import com.hshit.downloader.dao.Dao;
import com.hshit.downloader.entity.FileInfo;
import com.hshit.downloader.entity.LoadInfo;
import com.hshit.downloader.models.TrackInfo;
import com.hshit.downloader.services.Downloader;
import com.hshit.downloader.utils.Constants;
import com.hshit.downloader.utils.Logger;

public class DownloadStatusFragment extends BaseFragment {

	public static DownloadStatusFragment newInstance(int position) {
		DownloadStatusFragment f = new DownloadStatusFragment();
		Bundle b = new Bundle();
		b.putInt(Constants.TITLE_DOWNLOAD, BaseFragment.TAB_DOWNLOAD);
		f.setArguments(b);
		return f;
	}

	LoadMoreListView mLsDownload;
	
	DownLoadAdapter adapter;
	
	private Map<String, Downloader> downloaders = new HashMap<String, Downloader>();
	private Map<String, ProgressBar> ProgressBars = new HashMap<String, ProgressBar>();

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				String url = (String) msg.obj;
				int length = msg.arg1;
				ProgressBar bar = ProgressBars.get(url);
				if (bar != null) {
					bar.incrementProgressBy(length);
					if (bar.getProgress() == bar.getMax()) {
						LinearLayout layout = (LinearLayout) bar.getParent();
						layout.removeView(bar);
						ProgressBars.remove(url);
						downloaders.get(url).delete(url);
						downloaders.get(url).reset();
						downloaders.remove(url);

						ImageButton btn_start = (ImageButton) layout.findViewById(R.id.btn_start);
						ImageButton btn_pause = (ImageButton) layout.findViewById(R.id.btn_pause);
						ImageButton btn_open = (ImageButton) layout.findViewById(R.id.btn_open);
						TextView mDivider = (TextView) layout.findViewById(R.id.item_download_divider);
						mDivider.setVisibility(View.VISIBLE);
						
						btn_open.setVisibility(View.VISIBLE);
						btn_pause.setVisibility(View.GONE);
						btn_start.setVisibility(View.GONE);
					}
				}
			}
		}
	};

	@Override
	public void setContentLayoutId() {
		mContentLayoutId = R.layout.fragment_download;

	}

	@Override
	public void onAfterView(View view) {
		mLsDownload = (LoadMoreListView) view.findViewById(R.id.ls_download);

	}
	
	List<Map<String, String>> data = new ArrayList<Map<String, String>>();
	public void showListView(TrackInfo item) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("link", item.getTrack_link());
		map.put("name", item.getTrack_name());
		map.put("singer", item.getSinger());
		data.add(map);
		if(adapter == null) {
			adapter = new DownLoadAdapter(getActivity(), data, mCallBack);
			mLsDownload.getListView().setAdapter(adapter);
		} else
			adapter.notifyDataSetChanged();
	}
	
	private CallBackPressDownload mCallBack = new CallBackPressDownload() {
		@Override
		public void onClickDownload(String url, String name, String singer, View v) {
			String localfile = Constants.DEFAULT_FOLDER + name + ".mp3";
			DownloadTask downloadTask = new DownloadTask(v);
			downloadTask.execute(url, localfile, "4", name, singer);
		}
		
		@Override
		public void onClickPause(String url, View v) {
			downloaders.get(url).pause();
			ImageButton btn_start = (ImageButton) ((View) v.getParent()).findViewById(R.id.btn_start);
			ImageButton btn_pause = (ImageButton) ((View) v.getParent()).findViewById(R.id.btn_pause);
			btn_pause.setVisibility(View.GONE);
			btn_start.setVisibility(View.VISIBLE);
		}
	};

	class DownloadTask extends AsyncTask<String, Integer, LoadInfo> {
		Downloader downloader = null;
		View v = null;
		String urlstr = null;

		public DownloadTask(final View v) {
			this.v = v;
		}

		@Override
		protected void onPreExecute() {
			ImageButton btn_start = (ImageButton) ((View) v.getParent()).findViewById(R.id.btn_start);
			ImageButton btn_pause = (ImageButton) ((View) v.getParent()).findViewById(R.id.btn_pause);
			btn_start.setVisibility(View.GONE);
			btn_pause.setVisibility(View.VISIBLE);
		}

		@Override
		protected LoadInfo doInBackground(String... params) {
			urlstr = params[0];
			String localfile = params[1];
			int threadcount = Integer.parseInt(params[2]);
			downloader = downloaders.get(urlstr);
			if (downloader == null) {
				downloader = new Downloader(urlstr, localfile, threadcount, getActivity(), mHandler);
				Dao.getInstance(getActivity()).saveInfosFileCompleted(new FileInfo(params[3], params[4], urlstr, localfile));
				downloaders.put(urlstr, downloader);
			}
			if (downloader.isdownloading())
				return null;
			return downloader.getDownloaderInfors();
		}

		@Override
		protected void onPostExecute(LoadInfo loadInfo) {
			if (loadInfo != null) {
				showProgress(loadInfo, urlstr, v);
				downloader.download();
			}
		}

	};

	private void showProgress(LoadInfo loadInfo, String url, View v) {
		ProgressBar bar = ProgressBars.get(url);
		if (bar == null) {
			bar = new ProgressBar(getActivity(), null,
					android.R.attr.progressBarStyleHorizontal);
			bar.setMax(loadInfo.getFileSize());
			bar.setProgress(loadInfo.getComplete());
			bar.getProgressDrawable().setColorFilter(getActivity().getResources().getColor(R.color.app_color), Mode.SRC_IN);//(Color.RED, Mode.SRC_IN);
			ProgressBars.put(url, bar);
			TextView mDivider = (TextView) ((LinearLayout) ((LinearLayout) v.getParent()).getParent()).findViewById(R.id.item_download_divider);
			mDivider.setVisibility(View.GONE);
			LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, 13);
			((LinearLayout) ((LinearLayout) v.getParent()).getParent())
					.addView(bar, params);
		}
	}

}
